const router = require("koa-router")()

const { getUserIdByContext } = require("../token")
const ArticleBasic = require("../../model/ArticleBasic")
const JSONBig = require("json-bigint") // 处理大数字插件

const isLine = require("is-online")
const axios = require("axios")
axios.defaults.transformResponse = [
  function (data) {
    //  当后台 响应的字符串 回到axios请求时 就会触发
    //  data是一个字符串  把字符串转化成 对象并且返回 默认的是JSON.parse()
    // 如果data是一个空字符串  直接转化就会报错
    // return data ? JSONBig.parse(data) : {}
    try {
      return JSONBig.parse(data)
    } catch (error) {
      return data // 如果失败 就把字符串直接返回
    }
  },
]
const url = "http://toutiao-app.itheima.net/v1_0/search"

// 获取搜索结果
router.get("/", async (ctx) => {
  // 如果用户未登录 返回默认的频道数据
  let { page = 1, per_page = 10, q } = ctx.request.query
  page = parseInt(page) // 当前页码
  per_page = parseInt(per_page) // 每页条数
  if (!q) {
    return { message: "搜索关键词不能为空", success: false, status: 400 }
  }
  try {
    // 检查网络状态
    throw new Error("线上故障！！！")
    await isLine()
    console.log("当前联网, 请求线上搜索接口")
    let {
      data: {
        data: { results, total_count },
      },
    } = await axios({ url, params: { q, page, per_page } })
    results = results.map((item) => {
      // 给线上的数据的id增加一个特殊标记
      return {
        ...item,
        art_id: "l-" + item.art_id,
      }
    })
    return { data: { page, per_page, results, total_count } }
  } catch (error) {
    console.log("当前断网, 执行线下搜索接口")
    const total_count = await ArticleBasic.find({
      title: new RegExp(q),
    }).countDocuments()
    let searchList = await ArticleBasic.aggregate([
      {
        $lookup: {
          from: "user_basic",
          localField: "user_id",
          foreignField: "user_id",
          as: "userInfo",
        },
      },
      {
        $match: {
          title: new RegExp(q),
        },
      },
      {
        $skip: (page - 1) * per_page,
      },
      {
        $limit: per_page, // 限制数量
      },
    ])
    searchList = searchList.map((item) => ({
      art_id: item.article_id,
      title: item.title,
      aut_id: item.user_id,
      aut_name:
        item.userInfo && item.userInfo.length ? item.userInfo[0].user_name : "",
      comm_count: item.comment_count,
      pubdate: item.create_time,
      cover:
        item.cover && item.cover.split(",").length
          ? {
              type: item.cover.split(",").length,
              images: item.cover.split(","),
            }
          : { type: 0 },
      like_count: 0,
      collect_count: 0,
    }))
    ctx.status = 200
    return { data: { page, per_page, results: searchList, total_count } }
  }
})

module.exports = router.routes()
